<template>
  <div>
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      :show-close="true"
      :append-to-body="true"
      :class="{'mobile-el-dialog': showMobilePage}"
      class="auto-common-dialog-size create-income-dialog"
      @close="closeDialog"
      @open="openDialog"
    >
      <div :style="{maxHeight:dialogMainHeight+'px'}" :class="{'is-mobile':showMobilePage}" class="create-income-scorll">
        <div v-if="!isCost" :style="!showMobilePage?{marginRight: '80px'}:''" class="create-income-item">
          <Title title="项目收入项" font-size="16px" style="margin: 0 0 16px"/>
          <el-form ref="incomeRuleForm" :model="incomeInfo" :rules="incomeRules" :label-width="labelWidth" class="lineHeight32" label-position="right">
            <el-form-item label="下单日期" prop="orderDate">
              <el-date-picker
                v-model="incomeInfo.orderDate"
                :clearable="true"
                :editable="false"
                type="date"
                placeholder="选择日期"
                value-format="timestamp"
                format="yyyy/MM/dd"
                size="small"
                @change="datePickerTime" />
            </el-form-item>
            <el-form-item label="项目类型" prop="projectType">
              <el-select
                v-model="incomeInfo.projectType"
                popper-class="global-select-down"
                name="orderForm"
                size="small"
              >
                <el-option
                  v-for="item in projectTypesOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id" />
                  <!-- <el-option
                  v-for="item in costItemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" /> -->
              </el-select>
            </el-form-item>
            <el-form-item label="含税金额(元)" prop="taxAmount">
              <el-input
                v-model="incomeInfo.taxAmount"
                name="taxAmount"
                type="number"
                oninput="if(value>999999999999)value=999999999999"
                size="small"
                placeholder="请输入含税金额"
                @change="numberInputChange(incomeInfo, 'taxAmount')"
                @mousewheel.native.prevent
              />
            </el-form-item>
            <el-form-item label="说明" prop="incomeRemark">
              <el-input
                :autosize="{minRows: 2, maxRows: 3}"
                v-model.trim="incomeInfo.incomeRemark"
                placeholder="请输入收入内容"
                resize="none"
                name="incomeRemark"
                type="textarea"
                maxlength="200"
                class="width240"
                style="word-break: break-word;font-size: 14px"
              />
            </el-form-item>
          </el-form>
        </div>
        <div :style="!isCost?{marginRight: '30px'}:''" class="create-income-item">
          <Title :title="costEdit?'编辑成本':'添加成本'" font-size="16px" style="margin: 0 0 16px" />
          <!-- 收入项的成本结算状态为待结算(0)或已忽略(5)时才能编辑 -->
          <el-form ref="costRuleForm" :disabled="!isCost && !(settlementStatus === 0 || settlementStatus === 5)" :model="costInfo" :rules="costRules" :label-width="labelWidth" class="lineHeight32" label-position="right">
            <el-form-item prop="costItemId" label="成本项">
              <el-select
                v-model="costInfo.costItemId"
                :clearable="!isCost"
                popper-class="global-select-down"
                name="costItemId"
                size="small"
                @change="setCostItem"
              >
                <el-option
                  v-for="item in costItemOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="申请人" prop="proposer">
              <selectWithUserLoad
                v-if="flag"
                ref="proposerRef"
                :disabled="!isCost && !costInfo.costItemId"
                v-model="costInfo.proposerObj"
                :hide-select-list="defaultProposer"
                :multiple="false"
                show-check-user
                key-name="id"
                value-type="object"
                class="width240"
                label-name="userName"
                filterable
              />
            </el-form-item>
            <el-form-item label="含税成本(元)" prop="costAmount">
              <el-input
                v-model="costInfo.costAmount"
                :disabled="!isCost && !costInfo.costItemId"
                placeholder="请输入成本金额"
                name="costAmount"
                type="number"
                oninput="if(value>999999999999)value=999999999999"
                size="small"
                @change="numberInputChange(costInfo, 'costAmount')"
                @mousewheel.native.prevent
              />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <selectWithoutHttp
                v-model="costInfo.supplierId"
                :disabled="!isCost && !costInfo.costItemId"
                :list-data="channelList"
                show-tool-tip="value"
                placeholder="请选择供应商"
                key-name="id"
                filterable
                clearable
                label-name="value"
                add-new
                add-new-str="添加新供应商"
                @addNewClick="toCreateSupplier"
                @changeInfo="supperlierChange"
              />
            </el-form-item>
            <el-form-item label="可抵扣税率">
              <div class="discount-input">
                <el-input
                  v-model="costInfo.discount"
                  :disabled="costInfo.isAuto === 1 || (!isCost && !costInfo.costItemId)"
                  :placeholder="costInfo.isAuto? (costPlaceholder?costPlaceholder:'根据所选供应商获取') : '请输入可抵扣税率'"
                  name="discount"
                  type="text"
                  size="small"
                  @input="deductionRateInput" >
                  <span slot="suffix" style="margin-right:5px;color:#333;">%</span>
                </el-input>
                <div class="switch-talent-mode">
                  <el-switch v-model="costInfo.isAuto" :active-value="1" :inactive-value="0" class="fb-switch" @change="switchChange"/>
                  <div class="text">{{ costInfo.isAuto?'自动':'手动' }}</div>
                </div>
              </div>
            </el-form-item>
            <el-form-item :prop="isCost ? 'costExplain' : ''" label="说明">
              <el-input
                :autosize="{minRows: 2, maxRows: 3}"
                :disabled="!isCost && !costInfo.costItemId"
                v-model.trim="costInfo.costExplain"
                placeholder="请输入成本内容"
                resize="none"
                name="costExplain"
                type="textarea"
                maxlength="200"
                class="width240"
                style="word-break: break-word;font-size: 14px"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" :disabled="btnLoading" class="ok" type="primary" @click="handelOk">确定</el-button>
        <el-button class="cancel-btn-style" type="info" style="font-size: 16px" @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex';

import Title from '@/components/Title';
import { hasRouteAuth } from '@/utils/permission';
import { channelList } from '@/api/select';
import { getProjectTypes } from '@/api/project';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import { costList } from '@/api/config';
import ElMessage from '@/utils/message';

export default {
  name: 'CreateIncomeDialog',
  components: { Title, selectWithoutHttp, selectWithUserLoad },
  props: {
    isCost: {
      type: Boolean,
      default: false
    },
    btnLoading: {
      type: Boolean,
      default: false
    },
    isSubmit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      loading: false,
      incomeRules: {
        'orderDate': [{ required: true, message: '请选择下单时间', trigger: 'change' }],
        'projectType': [{ required: true, message: '请选择项目类型', trigger: 'change' }],
        'taxAmount': [{ required: true, message: '请输入含税金额', trigger: 'change' }]
      },
      costItemOptions: [],
      projectTypesOptions: [],
      channelList: [],
      id: '',
      antiShakeTime: 0, // 防抖时间
      incomeInfo: {
        orderDate: new Date().getTime(),
        projectType: '',
        incomeRemark: '',
        taxAmount: ''
      },
      costInfo: {
        costItemId: '',
        costExplain: '',
        costAmount: '',
        supplierId: '',
        discount: '',
        isAuto: 1,
        proposerObj: {}
      },
      flag: true,
      defaultProposer: [], // 默认申请人
      dialogMainHeight: '',
      isIncome: 0,
      costPlaceholder: '',
      selectSupplier: null,
      settlementStatus: 0,
      costEdit: true,
      selectCostItem: {}
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    labelWidth() {
      return '110px';
    },
    costRules() {
      const validateCostItem = (msg) => {
        return (rule, value, callback) => {
          const marketId = this.costInfo.costItemId;
          if (!marketId || marketId === '') {
            callback(new Error(msg));
          } else {
            callback();
          }
        };
      };
      const params = {
        'costExplain': [{ required: true, message: '请填写说明', trigger: 'blur' }]
      };
      if (this.costInfo.costItemId && !this.isCost) {
        params.supplierId = [{ required: true, trigger: 'change', message: '请选择供应商' }];
      }
      if (this.isCost) {
        params.supplierId = [{ required: true, trigger: 'change', message: '请选择供应商' }];
        params.costItemId = [{ required: this.isCost, validator: validateCostItem('请输入成本项'), trigger: 'change' }];
      }
      return params;
    },
    formDataIsValid() {
      let isValid = true;
      if (!this.isCost) {
        const { incomeInfo: { orderDate, projectType, taxAmount }} = this;
        if (this.$refs.incomeRuleForm) {
          const { fields } = this.$refs.incomeRuleForm;
          let isCostValid = true;// 存在成本项需要校验成本表单
          if (this.costInfo.costItemId) {
            isCostValid = !!this.costInfo.supplierId;
          }
          isValid = !fields.some(item => item.validateState === 'error') && isCostValid;
        }
        const result = !!(orderDate && projectType && !(taxAmount === null || taxAmount === '') && isValid);
        return result;
      } else {
        const { costInfo: { costItemId, costExplain }} = this;
        if (this.$refs.costRuleForm) {
          const { fields } = this.$refs.costRuleForm;
          isValid = !fields.some(item => item.validateState === 'error');
        }
        const result = !!(costItemId && costExplain && isValid);
        return result;
      }
    }
  },
  watch: {
    'costInfo.costItemId': {
      handler: function(newV) {
        if (!newV) {
          this.$set(this.costInfo, 'proposerObj', {});
          this.$refs.costRuleForm.resetFields();
        }
        if (this.costInfo.proposerObj && !this.costInfo.proposerObj.id && newV) {
          this.$set(this.costInfo, 'proposerObj', { id: this.userInfo.id, userName: this.userInfo.userName });
          this.$forceUpdate();
        }
        this.$nextTick(() => {
          this.$refs.costRuleForm.clearValidate();
        });
      },
      deep: true
    }
  },
  methods: {
    getCostList() {
      const params = {
        page: 1,
        perPage: 100,
        costBelong: 1
      };
      costList(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items.forEach(i => {
            i.value = i.costId;
            i.label = i.costName;
          });
          this.costItemOptions = res.data.items;
        }
      });
    },
    closeDialog() {
      this.incomeInfo = {
        orderDate: new Date().getTime(),
        projectType: '',
        incomeRemark: '',
        taxAmount: ''
      };
      this.costInfo = {
        costItemId: '',
        costExplain: '',
        costAmount: '',
        supplierId: '',
        discount: '',
        isAuto: 1,
        proposerObj: {}
      };
      this.id = '';
      this.isIncome = false;
      this.dialogVisible = false;
      this.costPlaceholder = '';
      if (this.isCost) {
        this.$refs.costRuleForm.resetFields();
      } else {
        this.$refs.incomeRuleForm.resetFields();
      }
    },
    // 获取供应商的列表
    async getChannel() {
      return new Promise((resolve) => {
        channelList().then(res => {
          this.channelList = res.data;
          resolve(res.data);
        });
      });
    },
    handleClose() {
      if (this.isCost) {
        this.$refs.costRuleForm.resetFields();
      } else {
        this.$refs.incomeRuleForm.resetFields();
      }
      this.dialogVisible = false;
      this.selectSupplier = null;
    },
    openDialog() {
      this.flag = false;
      this.$nextTick(() => {
        this.flag = true;
      });
      this.costEdit = false;
      const clientHeight = window.innerHeight;
      this.dialogMainHeight = (clientHeight * 4) / 5;
      if (!this.costInfo.costItemId) {
        this.defaultProposer = [{
          id: this.userInfo.id,
          userName: this.userInfo.userName
        }];
      }
      if (this.isCost) {
        this.$set(this.costInfo, 'proposerObj', { id: this.userInfo.id, userName: this.userInfo.userName });
      }
      if (this.$refs.incomeRuleForm) this.$refs.incomeRuleForm.clearValidate();
      if (this.$refs.costRuleForm) this.$refs.costRuleForm.clearValidate();
      this.getProjectTypeOtions();
      this.getCostList();
      this.getChannel();
    },
    async initInfo(data) {
      try {
        const res = await channelList();
        this.channelList = res.data;
        this.getEditInfo(data);
      } catch (err) {
        console.log(err);
      }
    },
    getProjectTypeOtions() {
      const params = {
        type: Number(this.isCost)
      };
      getProjectTypes(params).then(res => {
        this.projectTypesOptions = res.data;
      });
    },
    // 确认
    handelOk() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 600) {
        return;
      }
      this.antiShakeTime = timestamp;
      if (this.isCost && !this.formDataIsValid) {
        this.$refs.costRuleForm.validate();
        this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
        return;
      } else if (!this.isCost && !this.formDataIsValid) {
        if (this.$refs.incomeRuleForm) this.$refs.incomeRuleForm.validate();
        if (this.$refs.costRuleForm) this.$refs.costRuleForm.validate();
        this.$message({ type: 'warning', message: '请检查信息是否填写完整' });
        return;
      }
      // 有选择成本才校验含税成本
      if (this.costInfo.costItemId) {
        if (Number(this.costInfo.costAmount) === 0 && !this.selectCostItem.canBeZero) {
          ElMessage.error('含税成本不能为0');
          return;
        }
        if (this.selectCostItem.canBeZero && this.costInfo.costAmount !== 0 && !this.costInfo.costAmount) {
          ElMessage.error('含税成本不能为空');
          return;
        }
      }
      if (this.isSubmit) {
        return;
      }
      let params;
      if (!this.isCost) {
        params = {
          ...this.incomeInfo,
          ...this.costInfo
        };
        params.costAmount = this.switchMoney(2, params.costAmount);
        params.taxAmount = this.switchMoney(2, params.taxAmount);
        params.orderDate = params.orderDate / 1000;
      } else {
        params = {
          ...this.costInfo
        };
        params.costAmount = this.switchMoney(2, params.costAmount);
      }
      params.proposerId = this.costInfo.proposerObj.id;// 3.0.2申请人
      params.proposer = this.costInfo.proposerObj.userName;
      if (this.id) {
        this.$emit('editItem', params);
      } else {
        this.$emit('addItem', params);
      }
    },
    handleSuccess(type) {
      this.$emit('success'); // 编辑，新建后刷新列表
      this.dialogVisible = false;
      this.$message({ type: 'success', message: !type ? '编辑成功' : '新建成功' });
    },
    getEditInfo(data) {
      this.costEdit = true;
      this.id = data.id;
      if (!this.isCost) {
        const { settlementStatus, orderDate, projectType, costItemId, incomeRemark, taxAmount, supplier, costExplain, costAmount, discount, isAuto, proposerId, proposer } = data;
        this.settlementStatus = settlementStatus || 0;
        this.incomeInfo = {
          orderDate: orderDate * 1000,
          projectType,
          incomeRemark,
          taxAmount: this.switchMoney(1, taxAmount)
        };
        this.costInfo = {
          costItemId,
          costExplain,
          costAmount: this.switchMoney(1, costAmount),
          supplierId: supplier ? supplier.id : null,
          discount: discount,
          isAuto
        };
        if (proposerId && proposer) {
          this.defaultProposer = [{// 3.0.2新增申请人
            id: proposerId,
            userName: proposer
          }];
          this.$set(this.costInfo, 'proposerObj', { id: proposerId, userName: proposer });
        }
      } else {
        const { costItemId, supplier, costExplain, discount: oldDiscount, costAmount, isAuto, isIncome, proposerId, proposer } = data;
        if (data.costItemId) this.setCostItem(data.costItemId);
        let discount = oldDiscount;
        if (isAuto) {
          discount = this.formatDiscount(supplier ? supplier.id : null);
        }
        this.defaultProposer = [{// 3.0.2新增申请人
          id: proposerId,
          userName: proposer
        }];
        this.costInfo = {
          costItemId,
          costExplain,
          discount: discount,
          isAuto,
          proposerObj: { id: proposerId, userName: proposer },
          costAmount: this.switchMoney(1, costAmount),
          supplierId: supplier ? supplier.id : null
        };
        this.isIncome = isIncome;
      }
      if (this.costInfo.isAuto === null) {
        this.costInfo.isAuto = 1;
      }
      if (this.costInfo.isAuto && this.costInfo.supplierId) {
        if (data.discount || data.discount === 0) {
          this.costPlaceholder = '';
        } else {
          this.costPlaceholder = '没有设置可抵扣税率';
        }
      } else {
        this.costPlaceholder = '';
      }
    },
    // 分转元， 元转分
    switchMoney(type, amount) {
      if (type === 1) { // 转换成元
        if (amount) {
          return amount / 100;
        } else {
          return amount;
        }
      }
      if (type === 2) { // 转换成分
        if (amount) {
          return Math.round(amount * 100);
        } else {
          return amount;
        }
      }
    },
    supperlierChange(data) {
      this.selectSupplier = data;
      if (data.discount || data.discount === 0) {
        this.costPlaceholder = '';
        this.costInfo.discount = data.discount;
      } else {
        this.costPlaceholder = '没有设置可抵扣税率';
        this.costInfo.discount = '';
      }
      this.newDiscount = data.discount;
      /* if (this.costInfo.isAuto) {
        if (data.discount || data.discount === 0) {
          this.costPlaceholder = '';
          this.costInfo.discount = data.discount;
        } else {
          this.costPlaceholder = '没有设置可抵扣税率';
          this.costInfo.discount = '';
        }
        this.newDiscount = data.discount;
      } else {
        this.costPlaceholder = '';
      } */
    },
    switchChange(value) {
      if (this.selectSupplier) {
        this.supperlierChange(this.selectSupplier);
      }
      this.costInfo.discount = value ? this.newDiscount : this.costInfo.discount;
    },
    datePickerTime(time) {
    },
    changeInput(value) {
      let str = value.replace(/[^\d.]/g, ''); // 只允许数字
      // str = value.replace(/^[0]/g, ''); // 不允许零
      str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
      str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
      str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
      str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
      str = str.replace(/^(\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      return str;
    },
    numberInputChange(row, key) {
      if (row[key]) row[key] = Number(row[key]).toFixed(2);
    },
    deductionRateInput(value) {
      let str = this.changeInput(value);
      if (Number(str) > 100) {
        if (str.substring(0, 3) === '100') {
          str = str.substr(0, 3);
        } else {
          str = str.substr(0, 2);
        }
      }
      this.costInfo.discount = str;
    },
    taxAmountInput(value) {
      let str = this.changeInput(value);
      if (Number(str) > 1000000000000000) {
        str = str.substr(0, 16);
      } else if (Number(str) === 0) {
        str = '';
      }
      this.incomeInfo.taxAmount = str;
    },
    costAmountInput(value) {
      let str = this.changeInput(value);
      if (Number(str) > 1000000000000000) {
        str = str.substr(0, 16);
      } else if (Number(str) === 0) {
        str = '';
      }
      this.costInfo.costAmount = str;
    },
    // 根据成本项设置对应信息
    setCostItem(item) {
      this.selectCostItem = this.costItemOptions.find(i => i.costId === item);
      // this.selectCostItem.costType = this.selectCostItem.costType ? Number(this.selectCostItem.costType) : this.selectCostItem.costType;
      // this.$refs.costDataForm.clearValidate();
    },
    // 获取供应商对应的可抵扣税率
    formatDiscount(supplierId) {
      this.newDiscount = null;
      if (supplierId) {
        for (let i = 0; i < this.channelList.length; i++) {
          if (this.channelList[i].id === supplierId) {
            this.newDiscount = this.channelList[i].discount;
            break;
          }
        }
      }
      return this.newDiscount;
    },
    // 新增供应商
    toCreateSupplier() {
      if (!hasRouteAuth('medium:supplier:edit')) {
        this.$message.error('您暂无供应商新增权限');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>
<style lang="scss" scoped>
.create-income-scorll {
  display: flex;
  .width240 {
    width: 240px;
  }
  &.is-mobile {
    flex-direction: column;
    @include scrollBar($x: hidden, $y: auto);
    &::v-deep {
      .el-input__inner,.width240 {
        width: 180px !important;
      }
      .discount-input {
        display: flex;
        flex-wrap: wrap;
        .switch-talent-mode {
          margin-left: 0;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.create-income-dialog {
  .switch-talent-mode {
    // position: absolute;
    // right: -110px;
    // top: 5px;
    margin-left: 10px;
    display: flex;
    align-items: center;
    .text {
      margin-left: 5px;
      font-size: 13px;
      color: #999;
    }
    .el-icon-warning-outline {
      color: #999;
      font-size: 13px;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
  .el-input__inner {
    height: 32px;
    line-height: 32px;
    width: 240px;
    font-size: 14px;
  }
  .discount-input {
    display: flex;
    .el-input {
      width: unset;
    }
    .el-input__inner {
      width: 150px !important;
    }
  }
  .el-form-item {
    .el-form-item__label {
      &::before {
        content: ' ';
        margin-right: 11px;
      }
    }
  }
}

</style>
